import React from 'react';
import { Button, message, Row, Col, Modal } from 'antd';
import { WeaTable, WeaErrorPage, WeaTools, WeaDialog, WeaRightMenu, WeaSearchGroup, WeaInput, WeaTextarea, WeaSelect,WeaLocaleProvider } from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
import ElementIndie from './ElementIndie';

class ElementPreview extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            eid: '',
        }
        this.onShow = this.onShow.bind(this);
    }
    onShow(eid){
    	this.setState({
    		visible: true,
            eid,
    	});
    }
    render() {
        const { visible, eid } = this.state;
        return <WeaDialog title={getLabel(387989,"元素预览")}
                  visible={visible}
                  closable={true}
                  onCancel={()=> this.setState({visible:false})}
                  icon='icon-coms-portal'
                  iconBgcolor='#1a57a0'
                  maskClosable={false}
                  buttons={[]}
                  style={{width: document.body.clientWidth * 0.4,height: 520 }}>
                  <div style={{padding:'10px'}}>
                    {eid ? <ElementIndie params={{eid, isSetting: true}}/> : ''}
                  </div>
        </WeaDialog>
    }
}

//门户组件
class ElementTemplate extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            title:getLabel(19408, '元素') ,
            elementtype: '1',
            name: '',
            desc: '',
            ebaseName: '',
            hpid: '',
            elementList: [],
            templateList: [],
            total: 0,
            selectedRowKeys: [],
            pageNum: 1,
            pageSize: 10,
            loading: false,
            portalList: [],
        }
        this.onChangeElementType = this.onChangeElementType.bind(this);
        this.getDataSource = this.getDataSource.bind(this);
        this.onShow = this.onShow.bind(this);
        this.onSave = this.onSave.bind(this);
        this.getButtons = this.getButtons.bind(this);
        this.getRightMenu = this.getRightMenu.bind(this);
        this.onRightMenuClick = this.onRightMenuClick.bind(this);
        this.handleElementPreview = this.handleElementPreview.bind(this);
    }
    componentWillMount(){
    	this.getDataSource();
    }
    onChangeElementType(value){
 		this.getDataSource({
    		elementtype: value,
    		title: value == '1' ? getLabel(19408, '元素') : getLabel(386539, '元素模板'),
    	    name: '',
            desc: '',
            ebaseName: '',
            hpid: '',
            selectedRowKeys: [],
            pageSize: 10,
            pageNum: 1,
        });
    }
    getDataSource(params = {}){
    	this.setState({loading:true});
    	const { elementtype, name, desc, hpid, ebaseName, pageNum, pageSize } = this.state;
    	if(!params.elementtype){
            params.elementtype = elementtype;
        }
       	if(!params.pageNum){
            params.pageNum = pageNum;
        }
        if(!params.pageSize){
            params.pageSize = pageSize;
        }
        if(params.name == undefined){
            params.name = name;
        }
        if(params.elementtype == '1'){
        	if(params.hpid == undefined){
	            params.hpid = hpid;
	        }
        }else if(params.elementtype == '2'){
        	if(params.desc == undefined){
	            params.desc = desc;
	        }
        }
        if(params.ebaseName == undefined){
            params.ebaseName = ebaseName;
        }
        WeaTools.callApi('/api/portal/elementtemplateadd/list', 'POST', params).then(result => {
            if(status == '2'){
                message.error(result.errormsg);
                return;
            }
            let state = {
            	total: result.total,
            	loading: false,
            }
            if(params.elementtype == '1') {
            	state.elementList = result.data;
            	state.portalList = result.portalList;
            }else if(params.elementtype == '2'){
            	state.templateList = result.data;
            }
            this.setState({...state, ...params});
        });
    }
    onSave(){
    	const { hpid, subCompanyId, handleRefreshPortal } = this.props;
    	const { elementtype, selectedRowKeys } = this.state;
        WeaTools.callApi('/api/portal/elementtemplateadd/save', 'POST', {
        	areaflag: 'A',
			hpid,
			subCompanyId,
			elementtype,
			ids: selectedRowKeys.join(),
        }).then(result => {
            if(status == '2'){
                message.error(result.errormsg);
                return;
            }
            handleRefreshPortal();
            this.setState({
            	visible: false,
	            title:getLabel(19408, '元素'),
	            elementtype: '1',
	            name: '',
	            desc: '',
	            ebaseName: '',
	            hpid: '',
	            elementList: [],
	            templateList: [],
	            total: 0,
	            selectedRowKeys: [],
	            pageNum: 1,
	            pageSize: 10,
	            loading: false,
	            portalList: []
	        });
            message.success(getLabel(83880,"添加成功！"));
        });
    }
    onShow(){
        this.setState({visible:true});
    }
    getButtons(){
        let btns = [];
        btns.push(<Button type="primary" onClick={() => this.getDataSource()}>{getLabel(197, '搜索')}</Button>);
        btns.push(<Button type="primary" onClick={this.onSave}>{getLabel(30986, '保存')}</Button>);
        btns.push(<Button onClick={()=>this.setState({visible:false})}>{getLabel(31129, '取消')}</Button>);
        return btns;
    }
    getRightMenu(){
        let btns = [];
        btns.push({
            icon: <i className='icon-coms-search'/>,
            content:getLabel(197, '搜索')
        });
        btns.push({
            icon: <i className='icon-coms-Journal'/>,
            content:getLabel(30986, '保存')
        });
        btns.push({
            icon: <i className='icon-coms-Add-to'/>,
            content:getLabel(31129, '取消')
        });
        return btns
    }
    onRightMenuClick(key){
        switch(key){
        	case '0':
                this.getDataSource();
                break;
            case '1':
                this.onSave();
                break;
            case '2':
                this.setState({visible:false});
                break;
        }
    }
   	handleElementPreview(eid){
   		this.refs.ElementPreview.onShow(eid);
    }
    render() {
        const { visible, title, total, elementtype, loading, elementList, templateList, name, desc, ebaseName, hpid, selectedRowKeys, pageNum, pageSize, portalList } = this.state;
        let items = [];
        items.push({com:<div className="portal-setting-left-elementtemplate-formitem"><Row>
              <Col span={8}><span className="portal-setting-left-elementtemplate-formitemLabel">{getLabel(20622,"模板类型")}</span></Col>
              <Col span={16}><WeaSelect value={elementtype} options={[{key: '1', showname: getLabel(19408, '元素')},{key: '2',  showname: getLabel(386539, '元素模板')}]} onChange={this.onChangeElementType}/></Col>
            </Row></div>});
        items.push({com:<div className="portal-setting-left-elementtemplate-formitem"><Row>
              <Col span={8}><span className="portal-setting-left-elementtemplate-formitemLabel">{getLabel(33439, '名称')}</span></Col>
              <Col span={16}><WeaInput value={name} onChange={value=>this.setState({name:value})}/></Col>
            </Row></div>});
        if(elementtype == '1'){
        	items.push({com:<div className="portal-setting-left-elementtemplate-formitem"><Row>
              <Col span={8}><span className="portal-setting-left-elementtemplate-formitemLabel">{getLabel(382252,"所属页面")}</span></Col>
              <Col span={16}><WeaSelect value={hpid} options={portalList} onChange={value=>this.getDataSource({hpid:value})}/></Col>
            </Row></div>});
        }else if(elementtype == '2'){
        	items.push({com:<div className="portal-setting-left-elementtemplate-formitem"><Row>
              <Col span={8}><span className="portal-setting-left-elementtemplate-formitemLabel">{getLabel(433, '描述')}</span></Col>
              <Col span={16}><WeaInput value={desc} onChange={value=>this.setState({desc:value})}/></Col>
            </Row></div>});
        }
        items.push({com:<div className="portal-setting-left-elementtemplate-formitem"><Row>
              <Col span={8}><span className="portal-setting-left-elementtemplate-formitemLabel">{getLabel(382251, '元素类型')}</span></Col>
              <Col span={16}><WeaInput value={ebaseName} onChange={value=>this.setState({ebaseName:value})}/></Col>
            </Row></div>});

        let html = <div/>;
        let _this = this;
  		const rowSelection = {
		  	onChange(selectedRowKeys) {
		    	_this.setState({selectedRowKeys})
		  	}
		};
		const pagination = {
	    	current: pageNum,
	    	pageSize,
			total,
			showSizeChanger: true,
			onChange: (goPage) => {
				this.getDataSource({pageNum: goPage});
			},
			onShowSizeChange(current, pageNum) {
				this.getDataSource({pageNum: current, pageSize: pageNum});
			}
		};
        if(elementtype == '1'){
        	const columns = [{
			  title: getLabel(33439, '名称'),
			  dataIndex: 'title',
			  key: 'title',
			  render: (text, record) => <a href="javascript:void(0)" title={getLabel(221, '预览')} onClick={() => this.handleElementPreview(record.id)}>{text}</a>,
			}, {
			  title: getLabel(382252,"所属页面"),
			  dataIndex: 'infoname',
			  key: 'infoname',
			}, {
			  title: getLabel(382251, '元素类型'),
			  dataIndex: 'ebasename',
			  key: 'ebasename',
			}];
        	html = <WeaTable needScroll={true} loading={loading} rowSelection={rowSelection} dataSource={elementList} columns={columns} pagination={pagination}/>
        } else if(elementtype == '2'){
        	const columns = [{
			  title: getLabel(33439, '名称'),
			  dataIndex: 'templatetitle',
			  key: 'templatetitle',
			}, {
			  title: getLabel(433, '描述'),
			  dataIndex: 'templatedesc',
			  key: 'templatedesc',
			}, {
			  title:getLabel(382251, '元素类型'),
			  dataIndex: 'ebasename',
			  key: 'ebasename',
			}];
        	html = <WeaTable needScroll={true} loading={loading} rowSelection={rowSelection} dataSource={templateList} columns={columns} pagination={pagination}/>
        }
        return <WeaDialog title={title} 
                  visible={visible}
                  closable={true}
                  onCancel={() => this.setState({visible:false})}
                  icon='icon-coms-portal'
                  iconBgcolor='#1a57a0'
                  maskClosable={false}
                  buttons={this.getButtons()}
                  style={{width:700,height:630}}>
                  <ElementPreview ref="ElementPreview"/>
                  <WeaRightMenu datas={this.getRightMenu()} onClick={this.onRightMenuClick}>
                    <WeaSearchGroup needTigger={true} title={getLabel(15774,"搜索条件")} showGroup={true} items={items}/>
                    {html}
                  </WeaRightMenu>
            </WeaDialog>
    }
}
class MyErrorHandler extends React.Component {
    render() {
        const hasErrorMsg = this.props.error && this.props.error !== "";
        return ( <WeaErrorPage msg={ hasErrorMsg ? this.props.error : getLabel(385218,"对不起，该页面异常，请联系管理员！") }/>
        );
    }
}
ElementTemplate = WeaTools.tryCatch(React, MyErrorHandler, {error: ""})(ElementTemplate);
export default ElementTemplate;







